package com.lhys.controller;

import com.lhys.common.ApiResultMsg;
import com.lhys.common.ResultInfo;
import com.lhys.dto.AssetUserDto;
import com.lhys.pojo.Asset;
import com.lhys.pojo.AssetUser;
import com.lhys.service.AssetUserService;
import com.lhys.utils.GenerateCodeUtils;
import com.lhys.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021/5/12
 * Time: 下午 14:58
 * Description: 登录控制器
 */
@Api(tags = "用户登录注册模块")
@RestController
public class LoginController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private GenerateCodeUtils generateCodeUtils;

    @Autowired
    private AssetUserService assetUserService;

    @Value("${login.password-error}")
    private String passwordErrorInfo;

    @PostMapping("/api/login")
    @ApiOperation(value = "登录/用户登录接口")
    @ApiResponses({
            @ApiResponse(code = 200, message = "登录成功"),
            @ApiResponse(code = 400, message = "账号或密码错误"),
    })
    public ApiResultMsg login(@RequestBody AssetUserDto assetUserDto) {
        AssetUser assetUser = new AssetUser();
        assetUser.setLoginName(assetUserDto.getLoginName());
        assetUser.setPassword(assetUserDto.getPassword());
        AssetUser loginAssetUser = assetUserService.getAssetUserByLoginNameAndPassword(assetUser);
        if (loginAssetUser == null) {
            return ApiResultMsg.error("该用户不存在");
        }
        if (loginAssetUser.getPassword().equals(passwordErrorInfo)) {
            return ApiResultMsg.error("账户或密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        loginAssetUser.setPassword(null);
        map.put("user", loginAssetUser);
        map.put("token", jwtUtils.generateToken(loginAssetUser.getUserId() + "", loginAssetUser.getUsername(), new Date()));
        return ApiResultMsg.success(ResultInfo.LOGIN_SUCCESS, map);
    }

    @GetMapping("/api/login-code")
    @ApiOperation("登录/获取登录验证码")
    public ApiResultMsg loginCode() {
        // 随机字符
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", generateCodeUtils.generateCode(99999, 10000));
        return ApiResultMsg.success(ResultInfo.SUCCESS, map);
    }
}